class Node {
  constructor(element, next) {
    this.element = element;
    this.next = next;
  }
}

class LinkedList {
  constructor(head, size) {
    this.head = null;
    this.size = 0;
  }
  _getNode(index) {
    if (index < 0 || index >= this.size) {
      throw new Error("越界");
    }
    let currentNode = this.head;
    for (let i = 0; i < index; i++) {
      currentNode = currentNode.next;
    }

    return currentNode;
  }
  add(index, element) {
    if (arguments.length === 1) {
      element = index;
      index = this.size;
    }
    if (index < 0 || index > this.size) {
      throw new Error("越界");
    }
    if (index === 0) {
      let head = this.head;
      this.head = new Node(element, head);
    } else {
      let preNode = this._getNode(index - 1);

      preNode.next = new Node(element, preNode.next);
    }
    this.size++;
  }
  remove(index) {
    if (index < 0 || index - 1 >= this.size) {
      throw new Error("越界");
    }
    if (index === 0) {
      this.head = this.head.next;
    } else {
      let zks = this._getNode(index);
      let preNode = this._getNode(index - 1); //上一个
      preNode.next = zks.next;
    }
    this.size--;
  }
}

let l1 = new LinkedList();
l1.add("node1");
l1.add("node2");
l1.add(1, "node3");
l1.remove(1);
console.log("结果", l1);
